//
//  HYVideoPlayerViewController.m
//  MusicMV
//
//  Created by Eternity on 16/3/18.
//  Copyright © 2016年 Eternity. All rights reserved.
//

#import "HYVideoPlayerViewController.h"
#import "AFHTTPRequestOperation.h"
#import "AFHTTPRequestOperationManager.h"
#import "LHYDownLoadManager.h"
#import "MBProgressHUD+show.h"
#import <AVFoundation/AVFoundation.h>
@interface HYVideoPlayerViewController ()<UITableViewDelegate , UITableViewDataSource>

@property (nonatomic , strong) UIImageView *backGroundImage;
@property (nonatomic , strong) UIVisualEffectView *visualEfView;
@property (nonatomic , strong) AVPlayer *player1;/**< 播放器对象 */
@property (nonatomic , strong) AVPlayerItem *playerItem; /**< 播放项目 */
@property (nonatomic , strong) AVPlayerLayer *playerLayer; /**< 用于显示播放器 */
@property (nonatomic , strong) UIBarButtonItem *buttonLeft;
@property (nonatomic , strong) UIView *playView;/**<播放视图*/
@property (nonatomic , strong) UILabel *timeLable;
@property (nonatomic , strong) UISlider *progressSlider;
@property (nonatomic , assign) CGFloat totalDuration;
@property (nonatomic , strong) UIView *bottomView;
@property (nonatomic , strong) UIButton *play;
@property (nonatomic , assign) BOOL isPlay;
@property (nonatomic , assign) BOOL isTap;
@property (nonatomic , strong) UIButton *fullButton;
@property (nonatomic , strong) UITableView *tableView;
@property (nonatomic , strong) UISegmentedControl *seg;
@property (nonatomic , strong) NSMutableArray *arrModel;
@property (nonatomic , strong) HYVideoPlayerModel *model;
@property (nonatomic , strong) NSMutableArray *arr1Model;
@property (nonatomic , strong) NSMutableArray *arrSameModel;
@property (nonatomic , strong) UIVisualEffectView *bottom;
@property (nonatomic , assign) NSInteger page;
@property (nonatomic , assign) BOOL isUpState;
@property (nonatomic , strong) UIButton *downLoadButton;
@property (nonatomic , copy) NSString *urlStr;
@property (nonatomic , strong) UIButton *doneButton;
@property (nonatomic , assign) BOOL isDownLoad;
@property (nonatomic , retain) NSMutableArray *arrDownLoad;
@property (nonatomic , strong) AFHTTPRequestOperation *operation1;
@property (nonatomic , assign, getter=isNowDownload) BOOL nowDownload;
@property (nonatomic , strong) UIProgressView *progressV;
@property (nonatomic , strong) UIButton *stopButton;
@property (nonatomic , assign) BOOL isSelect;


@end

@implementation HYVideoPlayerViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.arr1Model = [NSMutableArray array];
        _isPlay = YES;
        _isTap = YES;
    }
    return self;
}
- (void)dealloc
{
    _tableView.delegate = nil;
    _tableView.dataSource = nil;
}


//视图即将消失时 关闭视频播放器
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    
    
    [self.player1 replaceCurrentItemWithPlayerItem:nil];
    
    [_play setImage:[UIImage imageNamed:@"stop2"] forState:(UIControlStateNormal)];
    _isPlay = NO;
    [self.player1 pause];
    self.nowDownload = NO;
    
    // 暂停任务1
    [LHYDownLoadManager pauseWithOperation:self.operation1];
    
    
}

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.translucent = YES;
    NSMutableArray *arrTitle = [NSMutableArray array];
    self.arrDownLoad = [self getArr];
    
    for (NSDictionary *dic in self.arrDownLoad) {
        [arrTitle addObject:dic[@"title"]];
        
    }
    if ([arrTitle containsObject:self.titleNav]) {
        
        self.isDownLoad = YES;
    }else {
        self.isDownLoad = NO;
    }
    if (_isDownLoad) {
        _doneButton.alpha = 1;
        _downLoadButton.alpha = 0;
        _stopButton.alpha = 0;
        _progressV.alpha = 0;
    }else {
        _downLoadButton.alpha = 1;
        _doneButton.alpha = 0;
        _stopButton.alpha = 0;
        _progressV.alpha = 0;
    }

    
    
}

// 从本地获取下载的数组
- (NSMutableArray *)getArr {
    
    NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSLog(@"%@", pathArr);
    NSString *documentPath = [pathArr lastObject];
    NSString *arrPath = [documentPath stringByAppendingPathComponent:@"arrPath.list"];
    
    NSArray *arr = [NSArray arrayWithContentsOfFile:arrPath];
    NSMutableArray *arrM = [NSMutableArray arrayWithArray:arr];
    
    return arrM;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    NSMutableArray *arrTitle = [NSMutableArray array];
    self.arrDownLoad = [self getArr];
    
    for (NSDictionary *dic in self.arrDownLoad) {
        [arrTitle addObject:dic[@"title"]];
        
    }
    if ([arrTitle containsObject:self.titleNav]) {
        
        self.isDownLoad = YES;
    }else {
        self.isDownLoad = NO;
    }
    
    
    self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    self.view.backgroundColor= [UIColor blackColor];
    self.backGroundImage = [[UIImageView alloc] init];
    self.backGroundImage.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
    [_backGroundImage sd_setImageWithURL:[NSURL URLWithString:self.albumImg]];
    _backGroundImage.userInteractionEnabled = YES;
    self.visualEfView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    _visualEfView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
    _visualEfView.alpha = 1;
    _visualEfView.userInteractionEnabled = YES;
    UIView *viewBack = [[UIView alloc] initWithFrame:_backGroundImage.frame];
    viewBack.backgroundColor = [UIColor blackColor];
    viewBack.alpha = 0.6;
    [_backGroundImage addSubview:viewBack];
    [_backGroundImage addSubview:_visualEfView];
    
    [self.view addSubview:_backGroundImage];
    
    self.buttonLeft = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"goBack"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ]style:(UIBarButtonItemStylePlain) target:self action:@selector(buttonLeft:)];
    
    self.navigationItem.leftBarButtonItem = _buttonLeft;
    
    [self addAVPlayer];
    [self.player1 play];
    
    [self addprogressObserver];
    self.progressSlider.value = 0;
    self.timeLable.text = @"--:--/--:--";
    
    //    轻拍手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [_playView addGestureRecognizer:tap];
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,  HEIGHT / 2 - 70 * ht + 64, SCREEN_WIDTH, SCREEN_HEIGHT -   (HEIGHT / 2 - 70 * ht + 64 + 50 * ht)) style:(UITableViewStylePlain)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.bounces = NO;
    _tableView.showsVerticalScrollIndicator = NO;
    
    [_visualEfView addSubview:_tableView];
    _tableView.backgroundColor = [UIColor clearColor];
    self.bottom = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    _bottom.frame = CGRectMake(0,  HEIGHT / 2 - 70 * ht + 64, SCREEN_WIDTH, 40 * ht);
    _bottom.alpha = 1;
    _bottom.userInteractionEnabled = YES;
    [self.view addSubview:_bottom];
    UIView *viewBack1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40 * ht)];
    viewBack1.backgroundColor = [UIColor blackColor];
    viewBack1.alpha = 0.1;
    [_bottom addSubview:viewBack1];
    self.seg = [[UISegmentedControl alloc] initWithItems:@[@"MV简介",@"评论",@"相关MV"]];
    _seg.frame = CGRectMake(10 * wt,5 * ht, SCREEN_WIDTH - 20 * wt, 30 * ht);
    _seg.tintColor = RGBA(0, 210, 200, 1);
    [_seg setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:(UIControlStateSelected)];
    [_bottom addSubview:_seg];
    _seg.selectedSegmentIndex = 0;
    [_seg addTarget:self action:@selector(segAction:) forControlEvents:(UIControlEventValueChanged)];
    [_tableView registerClass:[HYDiscripitonTableViewCell class] forCellReuseIdentifier:@"HYDiscripitonTableViewCell"];
    [_tableView registerClass:[HYTalkTableViewCell class] forCellReuseIdentifier:@"HYTalkTableViewCell"];
    [_tableView registerClass:[HYSameTableViewCell class] forCellReuseIdentifier:@"HYSameTableViewCell"];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    if (_seg.selectedSegmentIndex == 0) {
        [self DataHandel];
    }
    if (_seg.selectedSegmentIndex == 1) {
        
        
        
    }
    if (_seg.selectedSegmentIndex == 2) {
        UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
        UIVibrancyEffect *vibrancyEffect = [UIVibrancyEffect effectForBlurEffect:blurEffect];
        self.tableView.separatorEffect = vibrancyEffect;
        [self DataHandel];
        
    }
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _isUpState = NO;
        
        [self DataHandelTalk];
        
    }];
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        _isUpState = YES;
        _page += 20;
        [self DataHandelTalk];
    }];
    
    self.downLoadButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _downLoadButton.frame = CGRectMake(SCREEN_WIDTH / 2 - 10 * wt, HEIGHT / 2 - 70 * ht + 64 + SCREEN_HEIGHT - (HEIGHT / 2 - 70 * ht + 64 + 50 * ht) + 10 * ht , 25 * wt, 25 * ht);
    [_downLoadButton setImage:[UIImage imageNamed:@"LHYDown"] forState:UIControlStateNormal];
    _downLoadButton.backgroundColor = [UIColor clearColor];
    [_visualEfView addSubview:_downLoadButton];
    [_downLoadButton addTarget:self  action:@selector(downLoadButton:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _doneButton.frame = CGRectMake(SCREEN_WIDTH / 2 - 10 * wt, HEIGHT / 2 - 70 * ht + 64 + SCREEN_HEIGHT - (HEIGHT / 2 - 70 * ht + 64 + 50 * ht) + 10 * ht , 25 * wt, 25 * ht);
    [_doneButton setImage:[UIImage imageNamed:@"likeLove"] forState:UIControlStateNormal];
    _doneButton.backgroundColor = [UIColor clearColor];
    [_visualEfView addSubview:_doneButton];
    [_doneButton addTarget:self  action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.stopButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _stopButton.frame = CGRectMake(SCREEN_WIDTH / 2 - 10 * wt, HEIGHT / 2 - 70 * ht + 64 + SCREEN_HEIGHT - (HEIGHT / 2 - 70 * ht + 64 + 50 * ht) + 10 * ht , 25 * wt, 25 * ht);
    [_stopButton setImage:[UIImage imageNamed:@"player2"] forState:UIControlStateNormal];
    _stopButton.backgroundColor = [UIColor clearColor];
    [_visualEfView addSubview:_stopButton];
    [_stopButton addTarget:self  action:@selector(stopButton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.progressV = [[UIProgressView alloc] initWithProgressViewStyle:(UIProgressViewStyleBar)];
    _progressV.frame =  CGRectMake(10 * wt,  HEIGHT - 10 * ht , SCREEN_WIDTH - 20 * wt, 40 * ht);
    
    // 改变默认高度
    _progressV.transform = CGAffineTransformMakeScale(1.0f, 3.0f);
    _progressV.backgroundColor = [UIColor clearColor];
    _progressV.progressImage = [UIImage imageNamed:@"222222.jpg"];
    _progressV.trackTintColor = [UIColor clearColor];
    [_visualEfView addSubview:_progressV];
    if (_isDownLoad) {
        _doneButton.alpha = 1;
        _downLoadButton.alpha = 0;
        _stopButton.alpha = 0;
        _progressV.alpha = 0;
    }else {
        _downLoadButton.alpha = 1;
        _doneButton.alpha = 0;
        _stopButton.alpha = 0;
        _progressV.alpha = 0;
    }
    
    
    
}

- (void)doneButton:(UIButton *)button{
    
    HYDownLoadViewController *hy = [[HYDownLoadViewController alloc] init];
    [self.navigationController pushViewController:hy animated:YES];
    
    
    
    
}




- (void)stopButton:(UIButton *)button {
    
    _isSelect = YES;
    if (_isSelect == YES) {
        _stopButton.alpha = 0;
        [_downLoadButton setImage:[UIImage imageNamed:@"stop2"] forState:(UIControlStateNormal)];
        _downLoadButton.alpha = 1;
        _isSelect = NO;
    }
    
    self.nowDownload = NO;
    
    // 暂停任务1
    [LHYDownLoadManager pauseWithOperation:self.operation1];
    
    
    
    
}


- (void)downLoadButton:(UIButton *)button {
    if (_isSelect == NO) {
        _stopButton.alpha = 1;
        _downLoadButton.alpha = 0;
    }
    
    // 禁止重复下载
    if (self.isNowDownload) return;
    self.nowDownload = YES;
    // 任务1
    NSString *string1 = self.shdUrl;
    NSString *string2 = @"?";
    NSRange range = [string1 rangeOfString:string2];
    NSInteger location = range.location;
    NSString *str = [string1 substringToIndex:location];
    
    self.operation1 = [LHYDownLoadManager downloadFileWithURLString:str cachePath:[NSString stringWithFormat:@"%lu.mp4",(unsigned long)[str hash]] progress:^(CGFloat progress, CGFloat totalMBRead, CGFloat totalMBExpectedToRead) {
        
        _progressV.alpha = 1;
        _progressV.progress = progress;
        NSLog(@"Task1 -> progress: %.2f -> download: %fMB -> all: %fMB", progress, totalMBRead, totalMBExpectedToRead);
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        
        NSDictionary *dic =@{@"photo":self.thumbImage,@"title":self.titleNav,@"filePath": str};
        
        
        
        NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSLog(@"%@", pathArr);
        NSString *documentPath = [pathArr lastObject];
        NSString *arrPath = [documentPath stringByAppendingPathComponent:@"arrPath.list"];
        
        NSArray *arr = [NSArray arrayWithContentsOfFile:arrPath];
        NSMutableArray *arrM = [NSMutableArray arrayWithArray:arr];
        
        [arrM addObject:dic];
        
        [arrM writeToFile:arrPath atomically:YES];
        
        _doneButton.alpha = 1;
        _downLoadButton.alpha = 0;
        _stopButton.alpha = 0;
        _progressV.alpha = 0;
        
        NSLog(@"Task1 -> Download finish");
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        _downLoadButton.alpha = 1;
        if (error.code == -999) NSLog(@"Task1 -> Maybe you pause download.");
        if (error) {
            
            [MBProgressHUD showErrorWithText:@"暂时不能下载该视频"];
            _stopButton.alpha = 0;
        }
        NSLog(@"Task1 -> %@", error);
    }];
    
    
    
    
    
}

- (void)segAction:(UISegmentedControl *)seg {
    NSInteger i = seg.selectedSegmentIndex;
    switch (i) {
        case 0:
            _tableView.bounces = NO;
            [_tableView reloadData];
            break;
        case 1:
            [self.arr1Model removeAllObjects];
            _page = 0;
            [self DataHandelTalk];
            break;
            
        case 2:
            _tableView.bounces = NO;
            [_tableView reloadData];
            break;
        default:
            
            break;
    }
    
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_seg.selectedSegmentIndex == 0) {
        
        return 1;
    }
    if (_seg.selectedSegmentIndex == 1) {
        return _arr1Model.count;
    }
    if (_seg.selectedSegmentIndex == 2) {
        return _arrSameModel.count;
    }
    
    return 0;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_seg.selectedSegmentIndex == 0) {
        CGSize size = [XRAFNetworkTool labelRectWithSize:CGSizeMake(SCREEN_WIDTH - 20 * wt, 0) LabelText:_model.Description Font:[UIFont systemFontOfSize:17]];
        return 110 * ht + size.height;
        
    }
    if (_seg.selectedSegmentIndex == 1) {
        HYTalkModel *talkModel = _arr1Model[indexPath.row];
        CGSize size = [XRAFNetworkTool labelRectWithSize:CGSizeMake(SCREEN_WIDTH - 20 * wt, 0) LabelText:talkModel.content Font:[UIFont systemFontOfSize:17]];
        
        return size.height + 70 * ht;
    }
    if (_seg.selectedSegmentIndex == 2) {
        return 100 * ht;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_seg.selectedSegmentIndex == 0) {
        HYDiscripitonTableViewCell *discripiton = [tableView dequeueReusableCellWithIdentifier:@"HYDiscripitonTableViewCell" forIndexPath:indexPath];
        discripiton.backgroundColor = [UIColor clearColor];
        discripiton.selectionStyle = UITableViewCellSelectionStyleNone;
        discripiton.headerImage.tag = 1000;
        discripiton.artistNameLabel.tag = 2000;
        discripiton.totalLabel.tag = 3000;
        discripiton.regdateLabel.tag = 4000;
        discripiton.totalLabel.text = [NSString stringWithFormat:@"播放总次数：%@", self.totoaView];
        discripiton.model = _model;
        return discripiton;
    }
    if (_seg.selectedSegmentIndex == 1) {
        HYTalkTableViewCell * talkCell = [tableView dequeueReusableCellWithIdentifier:@"HYTalkTableViewCell" forIndexPath:indexPath];
        talkCell.talkModel = _arr1Model[indexPath.row];
        talkCell.backgroundColor = [UIColor clearColor];
        talkCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return talkCell;
    } else {
        HYSameTableViewCell *sameCell = [tableView dequeueReusableCellWithIdentifier:@"HYSameTableViewCell" forIndexPath:indexPath];
        sameCell.backgroundColor = [UIColor clearColor];
        sameCell.model = _arrSameModel[indexPath.row];
        sameCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return sameCell;
    }
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    _progressV.progress = 0;

    if (_seg.selectedSegmentIndex == 0) {
        HYDetailViewController *detail = [[HYDetailViewController alloc] init];
        self.navigationController.navigationBar.translucent = NO;
        detail.AID = _model.artistId;
        detail.headerImage = _model.artistAvatar;
        detail.titleNav = _model.artistName;
        [self.navigationController pushViewController:detail animated:YES];
        
        
    }
    
    
    if (_seg.selectedSegmentIndex == 2) {
        
        HYVideoPlayerModel * model = _arrSameModel[indexPath.row];
        
        self.titleNav = model.title;
        self.urlID = model.ID;
        self.totoaView = model.totalViews;
        self.shdUrl = model.hdUrl;
        self.thumbImage = model.thumbnailPic;
        NSMutableArray *arrTitle = [NSMutableArray array];
        self.arrDownLoad = [self getArr];
        
        for (NSDictionary *dic in self.arrDownLoad) {
            [arrTitle addObject:dic[@"title"]];
            
        }
        if ([arrTitle containsObject:self.titleNav]) {
            
            self.isDownLoad = YES;
            
        }else {
            self.isDownLoad = NO;
            
        }
        
        
        if (_isDownLoad) {
            
            _doneButton.alpha = 1;
            _downLoadButton.alpha = 0;
        }else {
            _downLoadButton.alpha = 1;
            _doneButton.alpha = 0;
        }
        
        _stopButton.alpha = 0;
        
        self.nowDownload = NO;
        
        // 暂停任务1
        [LHYDownLoadManager pauseWithOperation:self.operation1];
        
        
        NSLog(@"%@",self.shdUrl);
        self.playerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:self.shdUrl]];
        [self.player1 replaceCurrentItemWithPlayerItem:_playerItem];
        [self DataHandel];
        
        
        
    }
    
    
    
    
    //push
    //    if (_seg.selectedSegmentIndex == 2) {
    //        HYVideoPlayerViewController * hy = [[HYVideoPlayerViewController alloc]init];
    //        HYVideoPlayerModel * model = _arrSameModel[indexPath.row];
    //
    //
    //        hy.titleNav = model.title;
    //        hy.urlID = model.ID;
    //        hy.shdUrl = model.hdUrl;
    //        hy.totoaView = model.totalViews;
    //  self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    //        self.navigationController.navigationBar.translucent = YES;
    //        [self.navigationController pushViewController:hy animated:YES];
    //    }
    
    
    
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_seg.selectedSegmentIndex == 2) {
        
        cell.alpha = 0.0;
        
        [UIView animateWithDuration:2 animations:^{
            cell.alpha = 1;
        }];
    }
    
    
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return @" ";
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40 * ht;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *bottom = [[UIView alloc] init];
    bottom.backgroundColor = [UIColor clearColor];
    return bottom;
    
}

- (void)fullButton:(UIButton *)button {
    if ([UIDevice currentDevice].orientation != UIDeviceOrientationPortrait) {
        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
        _bottom.hidden = NO;
        _seg.hidden = NO;
        self.playView.frame = CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, HEIGHT / 2 - 70 * ht);
        self.bottomView.frame = CGRectMake(0, SCREEN_HEIGHT / 2 - 105 * ht, WIDTH, 35 * ht);
        UIImageView *imageView = [_tableView viewWithTag:1000];
        imageView.frame = CGRectMake(10 * wt, 5 * ht, 50 * wt, 50 * ht);
        imageView.backgroundColor = [UIColor clearColor];
        imageView.layer.cornerRadius = 25;
        UILabel *name = [_tableView viewWithTag:2000];
        name.frame = CGRectMake(65 * wt, 20 * ht, SCREEN_WIDTH / 2, 20 * ht);
        UILabel *total = [_tableView viewWithTag:3000];
        total.frame = CGRectMake(10 * wt, 60 * ht, SCREEN_WIDTH, 20 * ht);
        UILabel *regData = [_tableView viewWithTag:4000];
        regData.frame = CGRectMake(10 * wt, 85 * ht, SCREEN_WIDTH, 20 * ht);
        self.playerLayer.frame =  CGRectMake(5, 5,[UIScreen mainScreen].bounds.size.width - 10,self.playView.frame.size.height -10);
        
        _play.frame = CGRectMake(20 * wt, 0, 30 * wt, 30 * ht);
        
        self.progressSlider.frame = CGRectMake(50 * wt, 0, WIDTH - 130 * wt, 30 * ht);
        
        self.timeLable.frame =CGRectMake(WIDTH - 80 * wt, 0, 80 * wt, 30 * ht);
        [_fullButton setImage:[UIImage imageNamed:@"Full"] forState:(UIControlStateNormal)];
        self.navigationController.navigationBarHidden = NO;
        
        self.fullButton.frame = CGRectMake(0, 5 , 20, 20);
        _visualEfView.userInteractionEnabled = YES;
        _backGroundImage.userInteractionEnabled = YES;
        _tableView.alpha = 1;
        _seg.hidden = NO;
    }else {
        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
        self.playerLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        _seg.hidden = YES;
        _bottom.hidden = YES;
        
        self.navigationController.navigationBarHidden = YES;
        self.playView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        _tableView.alpha = 0;
        //全屏后底部处理
        self.bottomView.frame = CGRectMake(0, SCREEN_HEIGHT * 5 / 6, SCREEN_WIDTH, SCREEN_HEIGHT / 6);
        [_fullButton setImage:[UIImage imageNamed:@"ExFull"] forState:(UIControlStateNormal)];
        
        //全屏后的播放功能view
        self.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        //视频大小
        self.playerLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        //视频进度条 总时间 全屏按钮
        self.play.frame = CGRectMake(25, 10, 50, 50);
        self.progressSlider.frame = CGRectMake(10 + _play.frame.size.width + 10, 26, SCREEN_WIDTH - 20 - self.timeLable.frame.size.width - _play.frame.size.width - 100, 20);
        self.timeLable.frame = CGRectMake(_play.frame.origin.x + 20 + _progressSlider.frame.size.width + 20 + 20, 12, 100, 50);
        _fullButton.frame = CGRectMake(5 * wt, 45 * ht, 10 * wt, 30 * ht);
        _visualEfView.userInteractionEnabled = YES;
        _backGroundImage.userInteractionEnabled = YES;
        
    }
    
    
}


- (void)tapAction:(UITapGestureRecognizer *)tap {
    if (_isTap == YES) {
        [UIView animateWithDuration:0.5 animations:^{
            self.bottomView.alpha = 0;
        }];
        
    }else {
        [UIView animateWithDuration:0.5 animations:^{
            self.bottomView.alpha = 1;
        }];
    }
    _isTap = !_isTap;
}


- (void)addAVPlayer{
    
    self.playView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, HEIGHT / 2 - 70 * ht)];
    [_visualEfView addSubview:_playView];
    _playView.backgroundColor = [UIColor blackColor];
    self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT / 2 - 105 * ht, WIDTH, 35 * ht)];
    [self.playView addSubview:_bottomView];
    self.progressSlider = [[UISlider alloc] initWithFrame:CGRectMake(50 * wt, 0, WIDTH - 130 * wt, 30 * ht)];
    [_bottomView addSubview:_progressSlider];
    
    self.timeLable = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH - 80 * wt, 0, 80 * wt, 30 * ht)];
    _timeLable.font = [UIFont systemFontOfSize:13];
    _timeLable.textColor = [UIColor lightTextColor];
    [_bottomView addSubview:_timeLable];
    
    self.fullButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _fullButton.frame = CGRectMake(0, 5, 20 * wt, 20 * ht);
    [_fullButton setImage:[UIImage imageNamed:@"Full"] forState:(UIControlStateNormal)];
    [_fullButton addTarget:self action:@selector(fullButton:) forControlEvents:(UIControlEventTouchUpInside)
     ];
    [_bottomView addSubview:_fullButton];
    
    
    self.play = [UIButton buttonWithType:UIButtonTypeCustom];
    _play.frame = CGRectMake(20 * wt, 0, 30 * wt, 30 * ht);
    [_play setImage:[UIImage imageNamed:@"player2"] forState:UIControlStateNormal];
    [_play addTarget:self  action:@selector(playAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [_bottomView addSubview:_play];
    
    [_progressSlider addTarget:self  action:@selector(progressAction:) forControlEvents:(UIControlEventValueChanged)];
    _progressSlider.tintColor = RGBA(30, 160, 130, 1);
    self.urlStr = self.shdUrl;
    
    _urlStr = [_urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:_urlStr];
    //    创建播放项目对象
    self.playerItem = [[AVPlayerItem alloc] initWithURL:url];
    //    创建播放器对象
    self.player1 = [[AVPlayer alloc] initWithPlayerItem:_playerItem];
    //    创建承载播放器的layer
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player1];
    //    [UIScreen mainScreen].bounds.size.height
    self.playerLayer.frame = CGRectMake(5, 5,[UIScreen mainScreen].bounds.size.width - 10,self.playView.frame.size.height -10);
    //   设置视频 填充模式
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    //    将播放器放到playView上
    [self.playView.layer insertSublayer:self.playerLayer atIndex:0];
    
    
    
    
}

#pragma mark - 播放进度监听
- (void)addprogressObserver {
    
    //    CMTime 是专门计算视频时间的格式
    // Core Media
    __weak typeof(self) weakSelf = self;
    [self.player1 addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        //        获取到总得视频时间
        CGFloat duration = CMTimeGetSeconds(weakSelf.playerItem.duration);
        //        获取到当前时间
        CGFloat current = CMTimeGetSeconds(weakSelf.playerItem.currentTime);
        
        //        把总时间转化为字符串 显示在lable上
        NSString *durationT = [NSString stringWithFormat:@"%02ld:%02ld", (NSInteger)duration/60,(NSInteger)duration % 60];
        NSString *currentT = [NSString stringWithFormat:@"%02ld:%02ld", (NSInteger)current/60, (NSInteger)current % 60];
        //        拼接字符串显示在lable上
        NSString *timeStr = [NSString stringWithFormat:@"%@/%@", currentT , durationT];
        weakSelf.timeLable.text = timeStr;
        //        slider 的value
        weakSelf.progressSlider.value = current / duration;
        
        //        记录总时间, slider 需要使用
        weakSelf.totalDuration = duration;
        
        if (current >= duration) {
            [LY_sharePlayeMusicHelp pause];
        }
    }];
    
}

- (void)progressAction:(UISlider *)slider {
    [_play setImage:[UIImage imageNamed:@"player2"] forState:(UIControlStateNormal)];
    
    //    获取到当前进度时间
    CGFloat currentTime = self.totalDuration * slider.value;
    //    转化为CMTime
    CMTime dragTime = CMTimeMake(currentTime, 1);
    
    [self.player1 seekToTime:dragTime completionHandler:^(BOOL finished) {
        //        到了时间之后开始播放
        [self.player1 play];
    }];
    
    
    
}


- (void)playAction:(UIButton *)button{
    
    
    if (_isPlay == YES) {
        [_play setImage:[UIImage imageNamed:@"stop2"] forState:(UIControlStateNormal)];
        [self.player1 pause];
    } else {
        [_play setImage:[UIImage imageNamed:@"player2"] forState:(UIControlStateNormal)];
        
        [self.player1 play];
    }
    _isPlay = !_isPlay;
    
    
    
}




- (void)buttonLeft:(UIBarButtonItem *)button {
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = RGBA(38,38, 38, 1);
    [self.player1 replaceCurrentItemWithPlayerItem:nil];
    [self.playerLayer removeFromSuperlayer];
    _playerLayer = nil;
    _playerItem = nil;
    _player1 = nil;
    self.navigationController.navigationBar.alpha = 1;
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)DataHandelTalk {
    NSDictionary *dic = @{@"App-Id":@"10101027",@"Device-Id":@"cb38b93ffda5c09483eaf6cda8874345"};
    //    NSLog(@"%@", self.urlID);
    
    [XRAFNetworkTool GETUrl:[NSString stringWithFormat:@"http://mapi.yinyuetai.com/video/comment/list.json?D-A=0&offset=%ld&size=20&v=2&videoId=%@",self.page,self.urlID] body:nil headFile:dic response:XRJSON success:^(NSURLSessionDataTask *task, id responseObject) {
        
        _tableView.bounces = YES;
        
        //        NSLog(@"%@",responseObject);
        NSArray *arr = responseObject[@"comments"];
        NSMutableArray *arrModel = [HYTalkModel modelWithArray:arr];
        for (HYTalkModel *model in arrModel) {
            [self.arr1Model addObject:model];
        }
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        [_tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
    
    
}


- (void)DataHandel {
    
    NSDictionary *dic = @{@"App-Id":@"10101027",@"Device-Id":@"cb38b93ffda5c09483eaf6cda8874345",@"Device-V":@" aVBob25lIE9TXzkuMV82NDAqMTEzNl8xMDAwMDEwMDBfaVBob25lIDU="};
    _tableView.bounces = NO;
    
    [XRAFNetworkTool GETUrl:[NSString stringWithFormat:@"http://mapi.yinyuetai.com/video/show.json?D-A=0&id=%@&relatedVideos=true&supportHtml=false&v=2",self.urlID] body:nil headFile:dic response:XRJSON success:^(NSURLSessionDataTask *task, id responseObject) {
        self.model = [HYVideoPlayerModel modelWithDic:responseObject];
        
        
        NSArray *arrSame = responseObject[@"relatedVideos"];
        self.arrSameModel = [HYVideoPlayerModel modelWithArray:arrSame];
        
        
        
        
        self.navigationItem.title  = self.titleNav;
        
        
        [_tableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
    
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
